<template>
  <div class="pager-container" v-if="totalPage >= 1">
    <Icon type="pageFirst" @click="handlerClick(1)" :disabled="current === 1" />
    <Icon
      type="pagePrev"
      @click="handlerClick(current - 1)"
      :disabled="current === 1"
    />
    <a
      v-for="n in pageShow"
      :key="n"
      @click="handlerClick(n)"
      :class="current === n ? 'active' : ''"
      >{{ n }}</a
    >
    <Icon
      type="pageNext"
      @click="handlerClick(current + 1)"
      :disabled="current === totalPage"
    />
    <Icon
      type="pageLast"
      @click="handlerClick(totalPage)"
      :disabled="current === totalPage"
    />
  </div>
</template>

<script>
import Icon from "@/components/Icon";
export default {
  name: "Pager",
  components: {
    Icon,
  },
  props: {
    current: {
      type: Number,
      default: 1,
    },
    total: {
      type: Number,
      default: 605,
    },
    limit: {
      type: Number,
      default: 10,
    },
    visibleNumber: {
      type: Number,
      default: 10,
    },
  },
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.limit);
    },
    pageShowMin() {
      let min = this.current - Math.floor(this.visibleNumber / 2);
      if (min < 1) {
        min = 1;
      }
      return min;
    },
    pageShowMax() {
      let max = this.pageShowMin + this.visibleNumber - 1;
      if (max > this.totalPage) {
        max = this.totalPage;
      }
      return max;
    },
    pageShow() {
      let pageArr = [];
      for (let i = this.pageShowMin; i <= this.pageShowMax; i++) {
        pageArr.push(i);
      }
      if (pageArr.length < this.visibleNumber) {
        let prevNum = this.visibleNumber - pageArr.length;
        pageArr = [];
        for (let i = this.pageShowMin - prevNum; i <= this.pageShowMax; i++) {
          pageArr.push(i);
        }
      }
      return pageArr;
    },
  },
  methods: {
    handlerClick(pageNumber) {
      if (pageNumber < 1) {
        pageNumber = 1;
      }
      if (pageNumber > this.totalPage) {
        pageNumber = this.totalPage;
      }
      if (this.current === pageNumber) {
        return;
      }
      this.$emit("pageChange", pageNumber);
    },
  },
};
</script>

<style lang="less" scoped>
@import "@/styles/var.less";
.pager-container {
  display: flex;
  justify-content: center;
  align-items: center;

  .icon-container,
  a {
    cursor: pointer;
    margin: 0 6px;
    &.active {
      color: @primary;
      font-weight: 800;
    }
  }
}
.icon-container {
  font-size: 30px;
  cursor: pointer;
  &.disabled {
    cursor: not-allowed;
    color: @lightWords;
    &:hover {
      color: @lightWords;
    }
  }
  &:hover {
    color: @primary;
  }
}
</style>
